<!DOCTYPE html>
<html>
<head>
  <title>webSocket聊天室</title>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  <link href="assets/css/bootstrap.min.css" rel="stylesheet">
  <script type="text/javascript">
    const config = {
      host: '127.0.0.1',
      port: '9501',
      path: '/'
    };
  </script>
</head>
<body>
<div class="container">
  <p>在线人数<span id="userNum"></span></p>
  <label for="message-box"></label>
  <textarea id="message-box" rows="10" readonly></textarea>
  <div class="send">
    <p><textarea id="input-box" placeholder="请输入要发送的内容"></textarea></p>
    <p style="color: #bd2c00" id="error-box"></p>
    <p><button type="button" class="btn btn-primary" id="sub-btn">发送</button></p>
  </div>
</div>
<script type="text/javascript">
  const $ = function (id) {
    return document.getElementById(id) || null
  }

  let handler = {
    isConnect: false,
    ws: null,
    init: function (input, btn, msgBox) {
      this.input = $(input)
      this.subBtn = $(btn)
      this.msgBox = $(msgBox)
      this.errBox = $('error-box')
    },
    onOpen: function (evt) {
      console.info("连接服务器成功")

      this.isConnect = true
    },
    onClose:function (evt) {
      console.log("Disconnected");
    },
    onError: function (evt) {
      console.error('Error occurs: ' + evt.data)
    },
    onMessage: function (evt) {
      let data = JSON.parse(evt.data);

      switch (data.type) {
        case 'text':
          handler._addMsg(data.msg);
          break;
        case 'num' :
          handler._updateUserNum(data.msg);
          break;
      }
      console.log('Received data from server: ' + evt.data)
    },
    sendMsg: function (self) {
      if( !this.isConnect ){
        return
      }

      this.errBox.value = ''

      if ( !this.input.value) {
        this.showErr('Can not submit empty data.')
        return
      }

      this.ws.send(this.input.value)
      this.input.value = ''
    },
    _addMsg: function (msg) {
      msg = JSON.parse(msg)

      this.msgBox.value += '用户' + msg.user + '说:\n' + msg.text + '\n'
      this.msgBox.scrollTop = this.msgBox.scrollHeight
    },
    _updateUserNum: function (msg) {
      $('userNum').innerText = msg
    },
    showErr: function (msg) {
      this.errBox.text = msg
    }
  }

  let simpleWS = {
    ws: null,
    handlers: {},
    connect: function (host, port) {
      const url = 'ws://' + host + ':' + port
      const ws = new WebSocket(url)

      ws.onopen = this.onOpen
      ws.onmessage = this.onMessage.bind(null, this)
      ws.onclose = this.onClose
      ws.onerror = this.onError

      this.ws = ws
      return this
    },
    onMessage: function (self, evt) {
      let ret = JSON.parse(evt.data);


    },
    onOpen: function (evt) {
      console.info("连接服务器成功", evt)

      this.isConnect = true
    },
    onClose:function (evt) {
      this.isConnect = false

      console.log("Disconnected", evt);
    },
    onError: function (evt) {
      console.error('Error occurs: ' + evt.data)
    },
    emit: function (cmd, data) {
      if( !this.isConnect ){
        return
      }

      this.ws.send('[' + cmd + ']:' + data)
    },
    route: function (route, cb) {
      this.handlers[route] = cb
    }
  }

  // connect
  //(function() {
//    const url = 'ws://' + config.host + ':' + config.port;
//    const wsClient = new WebSocket(url);
//    handler.ws = wsClient
//    handler.init('input-box', 'sub-btn', 'message-box')

    $('sub-btn').addEventListener('click', handler.sendMsg , false);

//    wsClient.onopen = handler.onOpen
//    wsClient.onmessage = handler.onMessage
//    wsClient.onclose = handler.onClose
//    wsClient.onerror = handler.onError

  const ws = simpleWS.connect(config.host, config.port)

  ws.route('chat', function (data) {
    const msgBox = $('message-box')
    data = JSON.parse(data)

    msgBox.value += '用户' + data.user + '说:\n' + data.text + '\n'
    msgBox.scrollTop = msgBox.scrollHeight
  })
  ws.route('count', function (data) {
    $('userNum').innerText = data
  })

  //})()
</script>
</body>
</html>
